package com.kobe.shirodemo.shiro;

import com.sun.xml.internal.bind.v2.TODO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * 创建 JYQ  on  2018/11/2,14:39
 */
public class RoleRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "RoleRealm";
    }

    @Override
    public boolean supports(AuthenticationToken token) {
//         如果使用SimpleToken 来登录 ,就由该Realm 处理登录逻辑
        return token instanceof  SimpleToken;
    }

    @Override
//    认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String) token.getPrincipal(); //主要
        String password = (String) token.getCredentials();// 凭证

//    TODO     查数据库

        if ("role".equals(username) && "123".equals(password)) {
//             登录成功
            AuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
            return info;
        } else {
//             登录失败
            throw new AuthenticationException("用户名或者密码错误");
        }
    }
    @Override
//     授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//     TODO 应该做的事,  去数据库查询所有的角色和权限
        Subject subject = SecurityUtils.getSubject();
        String username = (String)subject.getPrincipal();
//        为当前用户添加用户角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("admin");
        info.addRole("money");
//        info.addRoles();
        info.addStringPermission("admin:insert");
        info.addStringPermission("admin:query");
        info.addStringPermission("money:delete");
        info.addStringPermission("money:update");
        return info;
    }
}
